<template>
  <div class="card-container">
    <div class="search-container">
      <span class="search-label">车牌号码：</span>
      <el-input v-model="params.carNumber" clearable aria-placeholder="请输入内容" class="search-main" />
      <span class="search-label">车主姓名：</span>
      <el-input v-model="params.personName" clearable aria-placeholder="请输入内容" class="search-main" />
      <span class="search-label">状态：</span>
      <el-select v-model="params.cardStatus">
        <el-option v-for="item in cardStatusList" :key="item.id" :value="item.name" />
      </el-select>
      <el-button type="primary" class="search-btn" @click="select">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="addCard">添加月卡</el-button>
      <el-button @click="delAll">批量删除</el-button>
    </div>
    <div class="table">
      <el-table
        style="width: 100%;"
        :data="cardList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column type="index" label="序号" />
        <el-table-column label="车主名称" prop="personName" />
        <el-table-column label="联系方式" prop="phoneNumber" />
        <el-table-column label="车辆号码" prop="carNumber" />
        <el-table-column label="车辆品牌" prop="carBrand" />
        <el-table-column label="剩余有效天数" prop="totalEffectiveDate" />
        <el-table-column label="状态" prop="cardStatus" :formatter="formatStatus" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{row}">
            <el-button type="text" size="mini">续费</el-button>
            <el-button type="text" size="mini">查看</el-button>
            <el-button type="text" size="mini" @click="exitCard(row.id)">编辑</el-button>
            <el-button type="text" size="mini" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager,next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageCheck"
      />
    </div>
    <el-dialog
      title="月卡操作"
      :visible.sync="showDialog"
      width="80%"
      :before-close="cancel"
    >
      <div class="add-card">
        <header class="add-header">
          <el-page-header content="月卡" />
        </header>
        <main class="add-main">
          <div class="form-container">
            <div class="title">车辆信息</div>
            <div class="form">
              <el-form ref="carRef" :model="carInfoForm" :rules="carInfoRules" label-width="100px">
                <el-form-item label="车主姓名" prop="personName">
                  <el-input v-model="carInfoForm.personName" />
                </el-form-item>
                <el-form-item label="联系方式" prop="phoneNumber">
                  <el-input v-model="carInfoForm.phoneNumber" />
                </el-form-item>
                <el-form-item label="车辆号码" prop="carNumber">
                  <el-input v-model="carInfoForm.carNumber" />
                </el-form-item>
                <el-form-item label="车辆品牌" prop="carBrand">
                  <el-input v-model="carInfoForm.carBrand" />
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="form-container">
            <div class="title">最新一次月卡缴费信息</div>
            <div class="form">
              <el-form ref="feeRef" :model="feeForm" :rules="feeFormRules" label-width="100px">
                <el-form-item label="有效日期" prop="payTime">
                  <el-date-picker
                    v-model="feeForm.payTime"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
                <el-form-item label="支付金额" prop="paymentAmount">
                  <el-input v-model="feeForm.paymentAmount" />
                </el-form-item>
                <el-form-item label="支付方式" prop="paymentMethod">
                  <el-select v-model="feeForm.paymentMethod" clearable>
                    <el-option
                      v-for="item in payMethodList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </div>

        </main>
        <footer class="add-footer">
          <div class="btn-container">
            <el-button @click="reset">重置</el-button>
            <el-button type="primary" @click="confirmAdd">确定</el-button>
          </div>
        </footer>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// ,exitCardDetailAPI
import { getCardListAPI, delCardAPI, delAllCardAPI, createCardAPI, getCardDetailAPI, exitCardDetailAPI } from '@/api/user'
import { Message } from 'element-ui'
export default {
  name: 'Card',
  data() {
    return {
      params: {
        page: 1,
        pageSize: 5,
        carNumber: null, // 车辆号码
        personName: null, // 车主姓名
        cardStatus: null // 车辆状态
      },
      showDialog: false,
      cardId: null,
      cardList: [],
      total: 0,
      cardStatusList: [
        {
          id: null,
          name: '全部'
        },
        {
          id: 0,
          name: '可用'
        },
        {
          id: 1,
          name: '已过期'
        }
      ],
      selectedList: [],
      carInfoForm: {
        personName: '', // 车主姓名
        phoneNumber: '', // 联系方式
        carNumber: '', // 车牌号码
        carBrand: '' // 车辆品牌
      },
      carInfoRules: {
        personName: [
          {
            required: true, message: '请输入车主姓名', trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true, message: '请输入联系方式', trigger: 'blur'
          },
          { pattern: /^1[34578]\d{9}$/, message: '请输入正确格式手机号' }
        ],
        carNumber: [
          {
            required: true, message: '请输入车辆号码', trigger: 'blur'
          }, {
            validatoe: (rule, value, callback) => {
              const plateNumberRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使]{1}[A-Z]{1}[A-Z0-9]{5,6}$/
              if (plateNumberRegex.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的车牌号'))
              }
            }, trigger: 'blur'
          }
        ],
        carBrand: [
          {
            required: true, message: '请输入车辆品牌', trigger: 'blur'
          }
        ]
      },
      feeForm: {
        payTime: [],
        paymentAmount: null,
        paymentMethod: null
      },
      feeFormRules: {
        payTime: [
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ]
      },
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '线下'
        }
      ]
    }
  },
  mounted() {
    this.getCardList()
  },
  methods: {
    sizeChangeFn(val) {
      this.params.pageSize = val
      this.getCardList()
    },
    delAll() {
      this.$confirm('此操作将永久删除选择的月卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 未选择删除的 id，给提示
        if (this.selectedList.length === 0) {
          Message.warning('请选择要删除的月卡!')
        } else {
          // 处理id
          const ids = this.selectedList.map(item => item.id)
          console.log(ids)
          await delAllCardAPI(ids)
          this.getCardList()
          Message.success('批量删除成功')
        }
      })
    },
    del(id) {
      this.$confirm('此操作将永久删除该月卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delCardAPI(id)
        this.getCardList()
        Message.success('批量删除成功')
      })
    },
    async exitCard(id) {
      this.showDialog = true
      const res = await getCardDetailAPI(id)

      // 回填车辆信息表单
      const { carInfoId, personName, phoneNumber, carNumber, carBrand } = res
      this.carInfoForm = {
        personName, phoneNumber, carNumber, carBrand, carInfoId, isEdit: true
      }

      // 回填缴费信息表单
      const { rechargeId, cardStartDate, cardEndDate, paymentAmount, paymentMethod } = res.rechargeList[0]
      this.feeForm = {
        rechargeId,
        paymentAmount,
        paymentMethod,
        payTime: [cardStartDate, cardEndDate]
      }
    },
    reset() {
      this.$refs.carRef.resetFields()
      this.$refs.feeRef.resetFields()
    },
    async confirmAdd() {
      await this.$refs.carRef.validate()
      await this.$refs.feeRef.validate()
      const payload = {
        ...this.feeForm,
        ...this.carInfoForm,
        // 单独处理时间
        cardStartDate: this.feeForm.payTime[0],
        cardEndDate: this.feeForm.payTime[1]
      }
      // 删掉多余字段
      delete payload.payTime

      if (this.carInfoForm.isEdit) {
        delete payload.isEdit
        console.log(payload)
        await exitCardDetailAPI(payload)
        Message.success('修改成功')
      } else {
        delete payload.isEdit
        console.log(payload)
        await createCardAPI(payload)
        Message.success('添加成功')
      }
      this.getCardList()
      this.cancel()
    },
    async getCardList() {
      const res = await getCardListAPI(this.params)
      this.cardList = res.rows
      this.total = res.total
      this.cardList.forEach(item => {
        this.$set(item, 'isEdit', false)
      })
    },
    formatStatus(row) {
      const Map = {
        0: '可用',
        1: '已过期'
      }
      return Map[row.cardStatus]
    },
    pageCheck(val) {
      console.log(val)
      this.params.page = val
      console.log(this.params)
      this.getCardList()
      // this.params.page = page
      // this.getCardList()
    },
    sizeChange(pageSize) {
      this.params.pageSize = pageSize
      this.getCardList()
    },
    select() {
      this.params.page = 1
      this.getCardList()

      // 调用查询接口
      // todo
    },
    delCard(id) {
      this.$confirm('您确定要删除该卡片吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        await delCardAPI(id)
        this.$message.success('删除成功')
      })
    },
    addCard() {
      this.showDialog = true
    },
    handleSelectionChange(valList) {
      this.selectedList = valList
      console.log(this.selectedList)
    },
    cancel() {
      this.reset()
      this.showDialog = false
    }
  }

}
</script>
<style lang="scss" scoped>
.card-container{
    padding: 20px;
    background-color: #fff;
}
.search-container{
    display: flex;
    align-items: center;
    border-bottom: 1px solid reb(237,237,237,.9);
    padding-bottom: 20px;
}
.search-main{
    width: 220px;
    margin-right: 10px;
}
.search-btn{
    margin-left: 20px;
}
.create-container{
    margin: 10px 0px;
}
.page-container{
    padding: 4px 0px;
    text-align: right;
}
.form-container{
    padding: 0px 80px;
}
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview{
      img{
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
